package priv.xakml.demos.ftpserver;
import org.apache.ftpserver.ftplet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

import org.apache.ftpserver.ftplet.DefaultFtplet;

/**
 * @author lhx
 * @date 2021-04-10 18:26
 **/
public class MyFtplet extends DefaultFtplet {
    private static final Logger logger = LoggerFactory.getLogger(MyFtplet.class);

    @Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request)
            throws FtpException, IOException {
        //获取上传文件的上传路径
//        String path = session.getUser().getHomeDirectory();
        //获取上传用户
//        String name = session.getUser().getName();
        //获取上传文件名
//        String filename = request.getArgument();
//        logger.info("用户:'{}'，上传文件到目录：'{}'，文件名称为：'{}'，状态：开始上传~", name, path, filename);
        return super.onUploadStart(session, request);
    }


    @Override
    public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
            throws FtpException, IOException {

        String cmd = request.getCommand();
        logger.debug("Command: {}",cmd);
        //获取上传文件的上传路径
        String homeDirectory = session.getUser().getHomeDirectory();
        //获取上传用户
        String name = session.getUser().getName();
        //获取上传文件名
        String filename = request.getArgument();
        logger.debug("用户:'{}'，上传文件到目录：'{}'，文件名称为：'{}，状态：成功！'", name, homeDirectory, filename);
        FileSystemView systemView = session.getFileSystemView();
        FtpFile ftpFile = systemView.getWorkingDirectory();
        String fileFullName =homeDirectory + ftpFile.getAbsolutePath() +File.separator + filename;
        new Thread(new Runnable() {
            @Override
            public void run() {
                //TODO: 上传到oss
                try {
                    String url = new AliyunOssToolkit().uploadSimpleStream(new File(fileFullName));
                    logger.info("file on oss location={}",url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onUploadEnd(session, request);
    }

    @Override
    public FtpletResult onDownloadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
        //todo servies...
        return super.onDownloadStart(session, request);
    }

    @Override
    public FtpletResult onDownloadEnd(FtpSession session, FtpRequest request) throws FtpException, IOException {
        //todo servies...
        return super.onDownloadEnd(session, request);
    }
}
